<?php

use sef\model;

/**
 * 文件模型
 * 负责文件的下载和上传
 */

class file_model extends model {
	public function upload($file) {
		/* 上传文件 */
		$ext = pathinfo($file['name'], PATHINFO_EXTENSION);

		$sha1 = sha1_file($file['tmp_name']);
		// $this -> check_ext($ext);
		// 如果是图像文件 检测文件格式
		if (in_array(strtolower($ext), array('gif', 'jpg', 'jpeg', 'bmp', 'png')) && false === getimagesize($file['tmp_name'])) {
			$this -> error = '非法图像文件';
			return false;
		}

		$size = $file['size'];
		//$this -> check_size($size);

		$file_name = $file['name'];

		$root_path = config('root_path');
		$root_path = 'uploads';
		$save_path = APP_NAME . DS . date('Y-m');
		$file_path = $root_path . DS . $save_path;
		$save_name = md5(microtime(true)) . bin2hex($file_name) . '.' . $ext;

		if (!is_dir($file_path)) {
			if (!mkdir($file_path, 0755, true)) {
				trigger_error('创建' . $file_path . '失败,请手工创建！', E_USER_ERROR);
			}
		}
		if (!rename($file['tmp_name'], $file_path . DS . $save_name)) {
			$this -> error = '文件上传保存错误！';
			return false;
		} else {
			$data = $file;
			unset($data['tmp_name']);
			unset($data['is_move']);
			unset($data['is_img_upload']);
			unset($data['type']);
			unset($data['error']);
			
			$data['mime'] = $file['type'];
			$data['ext'] = $ext;
			$data['sha1'] = $sha1;
			$data['create_time'] = time();
			$data['save_name'] = $save_name;
			$data['save_path'] = $save_path;
						
			$file['id'] = encrypt($this -> add($data));
			
			$file['save_name'] = $save_name;
			$file['save_path'] = $save_path;
			$file['url'] = str_replace("/", "\\", $root_path . DS . $save_path . DS . $save_name);
			return $file;
		}
	}

	public function download($id) {
		$file = $this -> find($id);
		if (!$file) {
			$this -> error = '找不到该文件！';
			return false;
		}
		$root_path = config('root_path');
		$root_path = 'uploads';
		$file_path = $root_path . DS . $file['save_path'] . DS . $file['save_name'];
		if (is_file($file_path)) {
			// /* 执行下载 */ //TODO: 大文件断点续传
			// header("Content-Type: application/force-download;");
			// header("Content-Description: File Transfer");
			// header('Content-type: ' . $file['mime']);
			// header('Content-Length:' . $file['size']);
			// $ua = $_SERVER['HTTP_USER_AGENT'];
			// if (preg_match('/MSIE/', $ua) || preg_match("/Trident\/7.0/", $ua)) {
			// header('Content-Disposition: attachment; filename="' . rawurlencode($file['name']) . '"');
			// } else {
			// header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
			// }
			// readfile($root_path . DS . $file['save_path'] . DS . $file['save_name']);
			//是否开启断点续传
			$fp = fopen($file_path, 'rb');
			$file_size = filesize($file_path);
			$ranges = $this -> get_range($file_size);

			header("Content-Type: application/force-download;");
			header("Content-Description: File Transfer");
			header('Content-type: ' . $file['mime']);
			$ua = $_SERVER['HTTP_USER_AGENT'];
			if (preg_match('/MSIE/', $ua) || preg_match("/Trident\/7.0/", $ua)) {
				header('Content-Disposition: attachment; filename="' . rawurlencode($file['name']) . '"');
			} else {
				header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
			}
			if ($ranges != null) {// 使用续传
				header('HTTP/1.1 206 Partial Content');
				header('Accept-Ranges:bytes');

				// 剩余长度
				header(sprintf('content-length:%u', $ranges['end'] - $ranges['start']));

				// range信息
				header(sprintf('content-range:bytes %s-%s/%s', $ranges['start'], $ranges['end'], $file_size));

				// fp指针跳到断点位置
				fseek($fp, sprintf('%u', $ranges['start']));
			} else {
				header('HTTP/1.1 200 OK');
				header('content-length:' . $file_size);
			}

			// fp指针跳到断点位置
			fseek($fp, sprintf('%u', $ranges['start']));
			while (!feof($fp)) {
				echo fread($fp, round(512 * 1024, 0));
				ob_flush();
				//sleep(1);
				// 用于测试,减慢下载速度
			}
			echo (1);
			return true;
			($fp != null) && fclose($fp);
		} else {
			$this -> error = '找不到该文件！';
			return false;
		}
	}

	private function get_range($file_size) {
		if (isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) {
			$range = $_SERVER['HTTP_RANGE'];
			$range = preg_replace('/[\s|,].*/', '', $range);
			$range = explode('-', substr($range, 6));
			if (count($range) < 2) {
				$range[1] = $file_size;
			}
			$range = array_combine(array('start', 'end'), $range);
			if (empty($range['start'])) {
				$range['start'] = 0;
			}
			if (empty($range['end'])) {
				$range['end'] = $file_size;
			}
			return $range;
		}
		return null;
	}

}
